let express = require('express');
let router = express.Router();
let model = require('../modles/index');
require('../util/util');

let User = model.Users;

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

// 登录
router.post('/login', function(req, res, next) {
    let params = {
        userName: req.body.userName,
        userPwd: req.body.userPwd,
    }

    User.findOne(params, function(err, userDoc) {
        if (err) res.json({
            status: '1',
            msg: err.message
        });
        else {
            if (userDoc) {
                // 保存登录信息
                res.cookie("userId", userDoc.userId, {
                    path: '/',
                    maxAge: 1000 * 60 * 60
                });
                res.cookie("userName", userDoc.userName, {
                    path: '/',
                    maxAge: 1000 * 60 * 60
                });

                // req.session.user = userDoc;

                res.json({
                    status: '0',
                    msg: '',
                    result: {
                        userName: userDoc.userName,
                    }
                });
            } else {
                res.json({
                    status: '1002',
                    msg: '用户名密码错误',
                    result: ''
                })
            }
        }
    });
});

// 登出
router.post('/logout', function(req, res, next) {
    res.cookie("userId", "", {
        path: "/",
        maxAge: -1
    });
    res.json({
        status: '0',
        msg: '',
        result: ''
    })
});

// 校验登录状态
router.get('/checkLogin', function(req, res, next) {
    if (req.cookies.userId) {
        res.json({
            status: '0',
            msg: '',
            result: {
                userName: req.cookies.userName
            }
        })
    } else {
        res.json({
            status: '1',
            msg: '未登录',
            result: ''
        })
    }
})

// 获取用户购物车列表
router.get('/cartList', function(req, res, next) {
    let userId = req.cookies.userId;
    User.findOne({"userId": userId}, function(err, userDoc) {
        if (err) res.json({
            status: '1',
            msg: err.message
        });
        else {
            if (userDoc) {
                res.json({
                    status: '0',
                    msg: '',
                    result: userDoc.cartList
                });
            }
        }
    });
});

// 获取购物车数量
router.get('/getCartCount', function(req, res, next) {
    if (req.cookies && req.cookies.userId) {
        var userId = req.cookies.userId;
        User.findOne({
            userId: userId
        }, function(err, doc) {
            if (err) res.json({
                status: '1',
                msg: err.message
            });
            else {
                var cartList = doc.cartList;
                let cartCount = 0;
                cartList.forEach((item) => {
                    cartCount += parseInt(item.productNum);
                })
                res.json({
                    status: '0',
                    msg: '',
                    result: cartCount
                });
            }
        })
    }
});

// 删除购物车
router.post('/cartDel', function(req, res, next) {
    let userId = req.cookies.userId;
    let productId = req.body.productId;

    User.update({
        userId: userId
    }, {
        $pull: {
            cartList: {
                productId: productId
            }
        }
    }, function(err, doc) {
        if (err) res.json({
            status: '1',
            msg: err.message
        });
        else {
            res.json({
                status: '0',
                msg: '',
                result: 'succ'
            });
        }
    })
});

// 编辑购物车
router.post('/cartEdit', function(req, res, next) {
    let userId = req.cookies.userId;
    let productId = req.body.productId;
    let productNum = req.body.productNum;
    let checked = req.body.checked;

    User.update({//条件
        "userId": userId,
        "cartList.productId": productId
    }, {//修改的 doc
        "cartList.$.productNum": productNum,
        "cartList.$.checked": checked
    }, function(err, doc) {
        if (err) res.json({
            status: '1',
            msg: err.message
        });
        else res.json({
            status: '0',
            msg: '',
            result: 'succ'
        });
    })
});

// 购物车全选
router.post('/editCheckAll', function(req, res, next) {
    let userId = req.cookies.userId;
    let chekAll = req.body.chekAll ? '1' : '0';

    User.findOne({
        userId: userId
    }, function(err, userDoc) {
        if (err) res.json({
            status: '1',
            msg: err.message
        });
        else {
            if (userDoc) {
                userDoc.cartList.forEach((item) => {
                    item.checked = chekAll
                });
                userDoc.save(function(err1, doc) {
                    if (err1) res.json({
                        status: '1',
                        msg: err1.message
                    });
                    else res.json({
                        status: '0',
                        msg: '',
                        result: 'succ'
                    });
                })
            }
        }
    })
});

// 获取用户地址
router.get('/addressList', function(req, res, next) {
    var userId = req.cookies.userId;
    User.findOne({userId: userId}, function(err, doc) {
        if (err) res.json({
            status: '1',
            msg: err.message
        });
        else {
            res.json({
                status: '0',
                msg: '',
                result: doc.addressList
            })
        }
    })
});

// 设置默认地址
router.post('/setDefault', function(req, res, next) {
    var userId = req.cookies.userId;
    var addressId = req.body.addressId;

    if (!addressId) res.json({
        status: '1003',
        msg: 'addressId is null'
    });
    else {
        User.findOne({userId: userId}, function(err, doc) {
            if (err) res.json({
                status: '1',
                msg: err.message
            });
            else {
                var addressList = doc.addressList;
                addressList.forEach((item) => {
                    if (item.addressId === addressId) {
                        item.isDefault = true;
                    } else {
                        item.isDefault = false;
                    }
                });
                doc.save(function(err1, doc1) {
                    if (err1) res.json({
                        status: '1',
                        msg: err1.message
                    });
                    else res.json({
                        status: '0',
                        msg: '',
                        result: ''
                    })
                })
            }
        })
    }

});

// 删除地址
router.post('/delAddress', function(req, res, next) {
    var userId = req.cookies.userId;
    var addressId = req.body.addressId;

    User.update({
        userId: userId
    }, {
        $pull: {
            'addressList': {
                addressId: addressId
            }
        }
    }, function(err, doc) {
        if (err) res.json({
            status: '1',
            msg: err.message,
            result: ''
        });
        else res.json({
            status: '0',
            msg: '',
            result: ''
        })
    })
})

// 订单
router.post('/payMent', function(req, res, next) {
    var userId = req.cookies.userId;
    var orderTotal = req.body.orderTotal;
    var addressId = req.body.addressId;

    User.findOne({
        userId: userId
    }, function(err, doc) {
        if (err) res.json({
            status: '1',
            msg: err.message,
            result: ''
        });
        else {
            var address = '';
            var goodsList = [];
            
            // 获取当前用户的地址信息
            doc.addressList.forEach(item => {
                if (addressId === item.addressId) address = item;
            })

            // 获取用户当前购物车购买的商品
            doc.cartList.filter(item => {
                if (item.checked === '1') {
                    goodsList.push(item);
                }
            });
            
            // 创建订单
            var platform = '622';
            var r1 = Math.floor(Math.random() * 10);
            var r2 = (Math.random()).toString().slice(-4);

            var sysDate = new Date().Format('yyyyMMddhhmmss');
            var createDate = new Date().Format('yyyy-MM-dd hh:mm:ss');

            // 订单
            var orderId = platform + r1 + sysDate + r2;

            var order = {
                orderId: orderId,
                orderTotal: orderTotal,
                addressInfo: address,
                goodsList: goodsList,
                orderStatus: '1',
                createDate: createDate
            }

            doc.orderList.push(order);

            doc.save(function(err1, doc1) {
                if (err1) res.json({
                    status: '1',
                    msg: err1.message,
                    result: ''
                });
                else res.json({
                    status: '0',
                    msg: '',
                    result: {
                        orderId: order.orderId,
                        orderTotal: order.orderTotal
                    }
                });
            });
        }
    });
});

// 订单详情
router.get('/orderDetail', function(req, res, next) {
    var userId = req.cookies.userId;
    var orderId = req.query.orderId;

    User.findOne({
        userId: userId
    }, function(err, userInfo) {
        if (err) res.json({
            status: '1',
            msg: err.message,
            result: ''
        });
        else {
            var orderList = userInfo.orderList;
            if (orderList.length > 0) {
                var orderTotal = ''
                orderList.forEach(item => {
                    if (item.orderId === orderId) {
                        orderTotal = item.orderTotal;
                    }
                });
                res.json({
                    status: '0',
                    msg: '',
                    result: {
                        orderId: orderId,
                        orderTotal: orderTotal
                    }
                });
            } else {
                res.json({
                    status: '10002',
                    msg: '订单不存在',
                    result: ''
                });
            }
        }
    })
});

module.exports = router;
